package com.wande.dataplatform.filecollection.validation.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.wande.dataplatform.filecollection.domain.dto.ValidationError;
import com.wande.dataplatform.filecollection.validation.IValidationRule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 枚举值校验规则
 * 校验字段值是否在允许的枚举值列表中
 * 配置格式: {"values": ["值1", "值2", "值3"], "caseSensitive": true}
 *
 * @author wande
 */
@Slf4j
@Component
public class EnumValidationRule implements IValidationRule {

    @Override
    public String getRuleType() {
        return "ENUM";
    }

    @Override
    public ValidationError validate(String fieldName, Object value, String ruleConfig) {
        // 如果值为空，跳过校验
        if (value == null) {
            return null;
        }

        try {
            JSONObject config = JSONUtil.parseObj(ruleConfig);
            List<String> allowedValues = config.getBeanList("values", String.class);
            boolean caseSensitive = config.getBool("caseSensitive", true);

            if (CollUtil.isEmpty(allowedValues)) {
                log.warn("枚举值校验规则配置缺少values参数");
                return null;
            }

            String valueStr = value.toString();
            boolean isValid = false;

            if (caseSensitive) {
                // 区分大小写
                isValid = allowedValues.contains(valueStr);
            } else {
                // 不区分大小写
                for (String allowedValue : allowedValues) {
                    if (allowedValue.equalsIgnoreCase(valueStr)) {
                        isValid = true;
                        break;
                    }
                }
            }

            if (!isValid) {
                return new ValidationError(
                    fieldName,
                    getRuleType(),
                    String.format("字段 [%s] 的值 %s 不在允许的枚举值列表中: %s", 
                        fieldName, valueStr, allowedValues),
                    value,
                    null
                );
            }

            return null;
        } catch (Exception e) {
            log.error("枚举值校验规则执行失败: {}", e.getMessage());
            return new ValidationError(
                fieldName,
                getRuleType(),
                String.format("字段 [%s] 枚举值校验失败: %s", fieldName, e.getMessage()),
                value,
                null
            );
        }
    }

    @Override
    public boolean isValidConfig(String ruleConfig) {
        try {
            JSONObject config = JSONUtil.parseObj(ruleConfig);
            List<String> values = config.getBeanList("values", String.class);
            
            // 必须配置至少一个枚举值
            return CollUtil.isNotEmpty(values);
        } catch (Exception e) {
            log.error("枚举值校验规则配置无效: {}", e.getMessage());
            return false;
        }
    }
}
